package com.jt.demo;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

/**
 * 秒杀练习:
 * 模拟两个线程抢同一张票
 *
 * */

public class SecondKillDemo02 {

    public static void seckill(){
        Jedis jedis = new Jedis("192.168.126.129",6379);
        jedis.watch("ticket","money");
        String ticket = jedis.get("ticket");

        if (ticket==null||Integer.valueOf(ticket)==0){
            throw new RuntimeException("票已卖完");
        }
        Transaction multi = jedis.multi();
        try {
            multi.decr("ticket");
            multi.incrBy("money", 100);
            multi.exec();
        }catch (Exception e){
            e.printStackTrace();
            multi.discard();
        }finally {
            jedis.unwatch();
            jedis.close();
        }

    }
    static void print(){
        Jedis jedis = new Jedis("192.168.126.129",6379);
        String ticket1 = jedis.get("ticket");
        String money = jedis.get("money");
        String name = Thread.currentThread().getName();
        System.out.println(name+"->"+ticket1+"->"+money);
        jedis.close();
    }


    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.126.129",6379);
        jedis.set("ticket", "1");
        jedis.set("money", "0");

        Thread t1 = new Thread(() ->{
            seckill();
            print();
        });
        Thread t2 = new Thread(()-> {
            seckill();
            print();
        });
        t1.start();
        t2.start();



    }


}
